package com.accompany.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;


import com.accompany.R;
import com.maning.updatelibrary.InstallUtils;

import java.text.DecimalFormat;


/**
 * Created by 29096 on 2018/10/16.
 */

public  class CheckedUpdateVersionData {
    private TextView start;
    private TextView cancels;
    private ProgressBar bar;
    private TextView updataing;
    private TextView totalText;
    private TextView currentText;
    View mMenuView;

    AlertDialog.Builder ald;
    AlertDialog dialog;
    public void updata(final Context context, String updataurl) {
        ald = showbarInActivity(context);
        dialog = ald.show();
        //下载APK
        InstallUtils.with(context)
                //必须-下载地址
                .setApkUrl(updataurl)
                //非必须-下载保存的文件的完整路径+/name.apk，使用自定义路径需要获取读写权限
                .setApkPath("")
                //非必须-下载回调
                .setCallBack(new InstallUtils.DownloadCallBack() {
                    @Override
                    public void onStart() {
                        //下载开始
                    }
                    @Override
                    public void onComplete(final String path) {

                        //下载完成
                        //先判断有没有安装权限---适配8.0
                        //如果不想用封装好的，可以自己去实现8.0适配
                        InstallUtils.checkInstallPermission((Activity) context, new InstallUtils.InstallPermissionCallBack() {
                            @Override
                            public void onGranted() {
                                //去安装APK
                                installApk(context,path);
                            }

                            @Override
                            public void onDenied() {
                                //弹出弹框提醒用户
                                AlertDialog alertDialog = new AlertDialog.Builder(context)
                                        .setTitle("温馨提示")
                                        .setMessage("必须授权才能安装APK，请设置允许安装")
                                        .setNegativeButton("取消", null)
                                        .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                //打开设置页面
                                                InstallUtils.openInstallPermissionSetting((Activity) context, new InstallUtils.InstallPermissionCallBack() {
                                                    @Override
                                                    public void onGranted() {
                                                        //去安装APK
                                                        installApk(context,path);
                                                    }

                                                    @Override
                                                    public void onDenied() {
                                                        //还是不允许咋搞？
                                                        Toast.makeText(context, "安装失败！", Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            }
                                        })
                                        .create();
                                alertDialog.show();
                            }
                        });

                    }

                    @Override
                    public void onLoading(long total, long current) {
                        //下载中
                        DecimalFormat df = new DecimalFormat("#.##");
                        double MaxNumber = Double.parseDouble(df.format((double) total / 1048576));
                        double MinNumber = Double.parseDouble(df.format((double) current / 1048576));
                        int num = (int) current;
                        int max = (int) total;
                        bar.setMax(max);
                        totalText.setText(MinNumber + "/" + MaxNumber + "(MB)");
                        currentText.setText(Integer.parseInt((current * 100) / total + "") + "%");
                        bar.setProgress(num);
                    }
                    @Override
                    public void onFail(Exception e) {
                        //下载失败
//                        dialog.dismiss();
                    }
                    @Override
                    public void cancle() {
                        //下载取消
                        cancleapk();
//                        dialog.dismiss();
                    }
                })
                //开始下载
                .startDownload();
    }
    @NonNull
    private AlertDialog.Builder showbarInActivity(Context context) {
        final AlertDialog.Builder ald = new AlertDialog.Builder(context);
        mMenuView = LayoutInflater.from(context).inflate(R.layout.updata_version_down,null);
        ald.setView(mMenuView);
        start = (TextView) mMenuView.findViewById(R.id.start);
        cancels = (TextView) mMenuView.findViewById(R.id.stops);
        bar = (ProgressBar) mMenuView.findViewById(R.id.progressBar);
        totalText = mMenuView.findViewById(R.id.total);
        currentText =  mMenuView.findViewById(R.id.current);
        updataing = (TextView) mMenuView.findViewById(R.id.updataing);
        cancels.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cancleapk();
                dialog.dismiss();
            }
        });
        return ald;
    }

    private void installApk(final Context context, String path) {
        //安装APK
        InstallUtils.installAPK((Activity) context, path, new InstallUtils.InstallCallBack() {
            @Override
            public void onSuccess() {
                //onSuccess：表示系统的安装界面被打开
                //防止用户取消安装，在这里可以关闭当前应用，以免出现安装被取消
                Toast.makeText(context, "正在安装程序", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFail(Exception e) {
                //安装出现异常，这里可以提示用用去用浏览器下载安装
                Toast.makeText(context, "安装失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void cancleapk(){
        InstallUtils.cancleDownload();
    }
}
